package com.woniu.cq.medical.service.impl;

import com.woniu.cq.medical.common.DateUtil;
import com.woniu.cq.medical.controller.component.CustomException;
import com.woniu.cq.medical.controller.form.RegisterForm;
import com.woniu.cq.medical.controller.form.RegisterListForm;
import com.woniu.cq.medical.controller.form.RegisterWindowForm;
import com.woniu.cq.medical.dao.*;
import com.woniu.cq.medical.entity.*;
import com.woniu.cq.medical.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2020-09-05
 */
@Service
@Slf4j
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, Register> implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private DutyService dutyService;

    @Autowired
    private DutyMapper dutyMapper;

    @Autowired
    private PatientService patientService;

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private TotalRegisterMapper totalRegisterMapper;

    @Autowired
    private AttendanceRecordMapper attendanceRecordMapper;

    @Autowired
    private AdministrativeWorkloadAccountMapper administrativeWorkloadAccountMapper;



    /**
     * 新增挂号
     * @param registerForm
     * @return
     */
    @Override
    public int insertRegister(RegisterForm registerForm) throws ParseException {
        /**
         * 先查询该身份证是否有记录 有则跳过 无则新增
         */
        Patient patient = patientService.queryCardIdRepetition(registerForm.getPatientIdCard());
        Patient patient1 = new Patient();
        if (patient!=null){
            log.info("有病人名单");
            patient1.setPatientId(patient.getPatientId());
        }else{
            patient1.setPatientName(registerForm.getPatientName());
            patient1.setPatientIdCard(registerForm.getPatientIdCard());
            log.info("set成功");
            int i = patientService.insertPatient(patient1);
            log.info("新增结果:"+i);
            if (i<=0){
                System.out.println("新增失败");
            }
        }


        /**
         * 查询该医生的挂号时间
         */
        List<Date> dates = dutyService.queryDutyDateList(registerForm.getDoctorId());
        log.info("检查时间");
        //用前端传过来的值匹配 得出挂号时间
        Date dayDate = DateUtil.getDayDate(registerForm.getValue(),dates);
       log.info("检查时间"+dayDate);
        LocalDate localDate = DateUtil.getLocalDate(dayDate);

        /**
         * 根据挂号时间和医生ID查询排班人数是否已满
         */
        Duty duty = dutyService.queryDutyFill(registerForm.getDoctorId(), localDate);
        if (duty.getBookPeopleMax()==duty.getNowBookPeople()){
            System.out.println("人数已满");
            //设置一个自定义异常
        }
        /**
         *  修改排班记录 新增预约人数+1
         */
        Integer nowBookPeople = duty.getNowBookPeople() + 1;
        Integer dutyId = duty.getDutyId();
        int i = dutyService.updateNowBookPeople(nowBookPeople,dutyId);
        System.out.println(i);
        if (i<=0){
            System.out.println("预约失败,修改医生排班记录失败");
        }
        Register register = new Register();

        /**
         * 创建挂号表实体对象 新增一个挂号表
         */
        //用户ID
        register.setPatientId(patient1.getPatientId());
        //添加医生ID
        register.setDoctorId(registerForm.getDoctorId());
        //添加科室
        register.setDepartmentId(registerForm.getAdministrativeId());
        //挂号时间
        register.setBookTime(localDate);
        //挂号方式
        register.setType("预约挂号");
        //挂号金额  查询缴费记录
       register.setMoney(registerForm.getDoctorRegisterCharge());
        //医生资质
        Doctor doctor = doctorMapper.findByDoctorId(registerForm.getDoctorId());
        register.setDoctorQualification(doctor.getDoctorDuty());
       //数据库新增时间
        Date date = new Date();
        LocalDate newDate = DateUtil.getLocalDate(date);
        register.setNewTime(newDate);
        register.setStatus("未就诊");
        register.setIsValid("未过号");
        int insert = registerMapper.insert(register);

        /**
         * 还需要添加挂号表ID  挂号总表
         */
        TotalRegister totalRegister = new TotalRegister();
        totalRegister.setRegisterId(register.getRegisterId());
        int insert1 = totalRegisterMapper.insert(totalRegister);
        if (insert1<=0){
            System.out.println("新增失败");
        }

        /**
         * 医生诊疗记录 候诊人数+1
         */
        AttendanceRecord attendanceRecord = attendanceRecordMapper.selectDoctorWaitCheckCount(registerForm.getDoctorId(),dayDate);
        if (attendanceRecord==null){
            throw new CustomException("IS NULL","空指针异常");
        }
        int waitCheckCount = attendanceRecord.getWaitCheckCount() + 1;
        Integer attendanceRecordId = attendanceRecord.getAttendanceRecordId();
        attendanceRecordMapper.updateWaitCheckCount(waitCheckCount,attendanceRecordId);
        LocalDate administrativeWorkloadAccountDate = DateUtil.getLocalDate(dayDate);
        /**
         * 科室诊疗记录 候诊+1
         */
        List<AdministrativeWorkloadAccount> AccountLists = administrativeWorkloadAccountMapper.selectDoctorIdAccount(registerForm.getDoctorId(),administrativeWorkloadAccountDate);
        if (AccountLists.size()>0){
            AdministrativeWorkloadAccount administrativeWorkloadAccount = AccountLists.get(0);
            int waitCheckCountNew = administrativeWorkloadAccount.getWaitCheckCount() + 1;
            int resultAccount = administrativeWorkloadAccountMapper.updateWaitCheckCount(administrativeWorkloadAccount.getAdministrativeWorkloadAccountId(), waitCheckCountNew);
            if (resultAccount>0){
                System.out.println("候诊人数添加成功");
            }

        }else {
           throw new CustomException("Not scheduling","科室未排班");
        }
        return insert;
    }

    /**
     * 根据身份证ID查询当天挂号记录 查询重复挂号
     * @param registerForm
     * @return
     * @throws ParseException
     */
    @Override
    public List<Register> queryRegisterRepetition(RegisterForm registerForm) throws ParseException {
        //查询该医生的挂号时间
        List<Date> dates = dutyService.queryDutyDateList(registerForm.getDoctorId());
        log.info("检查时间");
        //用前端传过来的值匹配 得出挂号时间
        Date dayDate = DateUtil.getDayDate(registerForm.getValue(),dates);
        log.info("检查时间"+dayDate);
        LocalDate localDate = DateUtil.getLocalDate(dayDate);
        List<Register> registers = registerMapper.queryRegisterRepetition(registerForm.getPatientIdCard(),localDate);
        return registers;
    }




    /**
     * 根据身份证查询挂号信息
     * @param patientIdCard
     * @return
     */
    @Override
    public List<RegisterListForm> queryRegisterList(String patientIdCard) {
        List<RegisterListForm> registerListForms = registerMapper.queryRegisterList(patientIdCard);
        return registerListForms;
    }

    /**
     * 窗口挂号
     * @param registerWindowForm
     * @return
     */
    @Override
    public int insertWindowRegister(RegisterWindowForm registerWindowForm) {
        /**
         * 先查询该身份证是否有记录 有则跳过 无则新增
         */
        Patient patient = patientService.queryCardIdRepetition(registerWindowForm.getPatientIdCard());
        Patient patient1 = new Patient();
        if (patient!=null){
            log.info("有病人名单");
            patient1.setPatientId(patient.getPatientId());
        }else{
            patient1.setPatientName(registerWindowForm.getPatientName());
            patient1.setPatientIdCard(registerWindowForm.getPatientIdCard());
            log.info("set成功");
            int i = patientService.insertPatient(patient1);
            log.info("新增结果:"+i);
            if (i<=0){
                System.out.println("新增失败");
            }
        }

        /**
         * 根据排班ID 查询出排班时间
         */
        Duty duty = dutyMapper.selectById(registerWindowForm.getDutyId());
        LocalDate dutyDate = duty.getDutyDate();
        if (duty.getBookPeopleMax()==duty.getNowBookPeople()){
            System.out.println("人数已满");
        }

        /**
         *  修改排班记录 新增预约人数+1
         */
        Integer nowBookPeople = duty.getNowBookPeople() + 1;
        Integer dutyId = duty.getDutyId();
        int i = dutyService.updateNowBookPeople(nowBookPeople,dutyId);
        System.out.println(i);
        if (i<=0){
            System.out.println("预约失败,修改医生排班记录失败");
        }
        /**
         * 创建挂号表实体对象 新增一个挂号表
         */
        Register register = new Register();
        //用户ID
        register.setPatientId(patient1.getPatientId());
        //添加医生ID
        register.setDoctorId(registerWindowForm.getDoctorId());
        //添加科室
        register.setDepartmentId(registerWindowForm.getAdministrativeId());
        //挂号时间
        register.setBookTime(dutyDate);
        //挂号方式
        register.setType("预约挂号");
        //挂号金额  查询缴费记录
        register.setMoney(registerWindowForm.getDoctorRegisterCharge());
        //医生资质
        Doctor doctor = doctorMapper.findByDoctorId(registerWindowForm.getDoctorId());
        register.setDoctorQualification(doctor.getDoctorDuty());
        //数据库新增时间
        Date date = new Date();
        LocalDate newDate = DateUtil.getLocalDate(date);
        register.setNewTime(newDate);
        register.setStatus("未就诊");
        register.setIsValid("未过号");
        int insert = registerMapper.insert(register);


        /**
         * 还需要添加挂号表ID  挂号总表
         */
        TotalRegister totalRegister = new TotalRegister();
        totalRegister.setRegisterId(register.getRegisterId());
        int insert1 = totalRegisterMapper.insert(totalRegister);
        if (insert1<=0){
            System.out.println("新增失败");
        }

        /**
         * 医生诊疗记录 候诊人数+1
         */
        Date dayDate = DateUtil.getDate(dutyDate);
        AttendanceRecord attendanceRecord = attendanceRecordMapper.selectDoctorWaitCheckCount(registerWindowForm.getDoctorId(),dayDate);
        if (attendanceRecord==null){
            throw new CustomException("IS NULL","空指针异常");
        }
        int waitCheckCount = attendanceRecord.getWaitCheckCount() + 1;
        Integer attendanceRecordId = attendanceRecord.getAttendanceRecordId();
        attendanceRecordMapper.updateWaitCheckCount(waitCheckCount,attendanceRecordId);

        /**
         * 科室诊疗记录 候诊+1
         */
        List<AdministrativeWorkloadAccount> AccountLists = administrativeWorkloadAccountMapper.selectDoctorIdAccount(registerWindowForm.getDoctorId(),dutyDate);
        if (AccountLists.size()>0){
            AdministrativeWorkloadAccount administrativeWorkloadAccount = AccountLists.get(0);
            int waitCheckCountNew = administrativeWorkloadAccount.getWaitCheckCount() + 1;
            int resultAccount = administrativeWorkloadAccountMapper.updateWaitCheckCount(administrativeWorkloadAccount.getAdministrativeWorkloadAccountId(), waitCheckCountNew);
            if (resultAccount>0){
                System.out.println("候诊人数添加成功");
            }
        }else {
            throw new CustomException("Not scheduling","科室未排班");
        }
        return insert;

    }

    @Override
    public List<Register> queryRegisterTwo(String patientIdCard,Integer dutyId) {
        List<Register> registers = registerMapper.queryRegisterTwo(patientIdCard, dutyId);
        return registers;
    }

    /**
     * 根据当前日期查询本月内未就诊名单
     * @param patientIdCard
     * @return
     * @throws ParseException
     */
    @Override
    public List<Register> queryRegisterThree(String patientIdCard,String status) throws ParseException {
        Date date = new Date();
        List<Date> thisMonth = DateUtil.getThisMonth(date);
        Date startTime = thisMonth.get(0);
        Date endTime = thisMonth.get(1);
        List<Register> registers = registerMapper.queryRegisterThree(patientIdCard, startTime, endTime, status);
        return registers;
    }


    @Override
    public boolean updateBatchById(Collection<Register> entityList) {
        return false;
    }
}
